package com.yeswater.multithread.chapter6;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * author : yeswater
 * date : 2023/11/1
 *
 * 使用枚举 enum 实现单例模式
 */

public class Run_6_1_8 {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();

        t1.start();
        t2.start();
        t3.start();
    }

    private static class MyThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println(MyObject.connectionFactory.getConnection());
            }
        }
    }

    private static enum MyObject {
        connectionFactory;

        private Connection connection;

        private static MyObject instance = null;

        private MyObject() {
            try {
                System.out.println("invoke build MyObject");
                String url = "jdbc:sqlserver://localhost:1079;databaseName=yeswater";
                String username = "1";
                String password = "2";
                String driveName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                Class.forName(driveName);
                connection = DriverManager.getConnection(url, username, password);
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
        }

        public Connection getConnection() {
            return connection;
        }
    }
}
